<template>
	<view class="follow-fans-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
			<view class="navbar-content">
				<view class="back-btn" @click="goBack">
					<uni-icons type="left" size="24" color="#333"></uni-icons>
				</view>
				<view class="navbar-title">{{ currentUser?.nickName || '用户' }}</view>
				<view class="placeholder"></view>
			</view>
		</view>

		<!-- Tab栏 -->
		<view class="tab-container">
			<view class="tab-list">
				<view 
					:class="['tab-item', activeTab === 'following' ? 'active' : '']"
					@click="switchTab('following')"
				>
					<text class="tab-text">关注</text>
				</view>
				<view 
					:class="['tab-item', activeTab === 'fans' ? 'active' : '']"
					@click="switchTab('fans')"
				>
					<text class="tab-text">粉丝</text>
				</view>
			</view>
			<view class="tab-indicator" :style="{ transform: `translateX(${activeTab === 'following' ? '0' : '100%'})` }"></view>
		</view>

		<!-- 内容区域 -->
		<scroll-view 
			class="content-scroll" 
			scroll-y 
			:refresher-enabled="true" 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
			@refresherrestore="onRestore"
		>
			<view class="content-container">
				<!-- 关注列表 -->
				<view v-if="activeTab === 'following'" class="user-list">
					<view v-if="loading" class="loading-container">
						<uni-load-more status="loading"></uni-load-more>
					</view>
					<view v-else-if="followingList.length === 0" class="empty-container">
						<view class="empty-icon">👥</view>
						<view class="empty-text">还没有关注任何人</view>
						<view class="empty-tip">去发现更多有趣的人吧</view>
					</view>
					<FollowUserCard
						v-else
						v-for="item in followingList"
						:key="item.id"
						:user-info="{
							userId: item.followedUserId,
							nickName: item.followedUserName,
							avatar: item.followedUserAvatar
						}"
						:is-following="true"
						:follow-id="item.id"
						@user-click="handleUserClick"
						@follow-change="handleFollowChange"
					/>
				</view>

				<!-- 粉丝列表 -->
				<view v-if="activeTab === 'fans'" class="user-list">
					<view v-if="loading" class="loading-container">
						<uni-load-more status="loading"></uni-load-more>
					</view>
					<view v-else-if="fansList.length === 0" class="empty-container">
						<view class="empty-icon">👤</view>
						<view class="empty-text">还没有粉丝</view>
						<view class="empty-tip">多发布优质内容吸引粉丝吧</view>
					</view>
					<FollowUserCard
						v-else
						v-for="item in fansList"
						:key="item.id"
						:user-info="{
							userId: item.fansId,
							nickName: item.fansName,
							avatar: item.fansAvatar
						}"
						:is-following="checkIsFollowing(item.fansId)"
						:follow-id="getFollowId(item.fansId)"
						@user-click="handleUserClick"
						@follow-change="handleFollowChange"
					/>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getFollowedByFansId, getFansByFollowedUserId, type UserFollowVO } from '@/api/follow/follow'
import useUserStore from '@/store/modules/user'
import FollowUserCard from './components/FollowUserCard.vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getWindowInfo()
const userStore = useUserStore()
const currentUser = computed(() => userStore.user)

// 页面参数
const userId = ref<number>(0)
const activeTab = ref<'following' | 'fans'>('following')

// 数据状态
const followingList = ref<UserFollowVO[]>([])
const fansList = ref<UserFollowVO[]>([])
const loading = ref(false)
const refreshing = ref(false)

// 页面加载时获取参数
onLoad((options) => {
	userId.value = Number(options?.userId || currentUser.value?.userId || 0)
	activeTab.value = (options?.activeTab as 'following' | 'fans') || 'following'
	
	if (userId.value) {
		loadData()
	}
})

// 切换Tab
const switchTab = (tab: 'following' | 'fans') => {
	activeTab.value = tab
	if ((tab === 'following' && followingList.value.length === 0) || 
		(tab === 'fans' && fansList.value.length === 0)) {
		loadData()
	}
}

// 加载数据
const loadData = async () => {
	if (loading.value) return
	
	loading.value = true
	try {
		if (activeTab.value === 'following') {
			const result = await getFollowedByFansId(userId.value)
			followingList.value = result.data || []
		} else {
			const result = await getFansByFollowedUserId(userId.value)
			fansList.value = result.data || []
		}
	} catch (error) {
		console.error('加载数据失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 加载所有数据（用于下拉刷新）
const loadAllData = async () => {
	try {
		// 同时加载关注列表和粉丝列表
		const [followingResult, fansResult] = await Promise.all([
			getFollowedByFansId(userId.value),
			getFansByFollowedUserId(userId.value)
		])
		
		followingList.value = followingResult.data || []
		fansList.value = fansResult.data || []
	} catch (error) {
		console.error('刷新数据失败:', error)
		uni.showToast({
			title: '刷新失败',
			icon: 'none'
		})
	}
}

// 下拉刷新
const onRefresh = async () => {
	refreshing.value = true
	try {
		await loadAllData()
	} finally {
		// 确保刷新状态被重置
		setTimeout(() => {
			refreshing.value = false
		}, 500) // 给一点延迟，让用户看到刷新完成
	}
}

const onRestore = () => {
	refreshing.value = false
}

// 检查是否已关注某个用户
const checkIsFollowing = (targetUserId: number): boolean => {
	return followingList.value.some(item => item.followedUserId === targetUserId)
}

// 获取关注记录ID
const getFollowId = (targetUserId: number): number | undefined => {
	const followItem = followingList.value.find(item => item.followedUserId === targetUserId)
	return followItem?.id
}

// 处理用户点击
const handleUserClick = (user: any) => {
	uni.navigateTo({
		url: `/pages/author/authorDetail?id=${user.userId}`
	})
}

// 处理关注状态变化
const handleFollowChange = async (targetUserId: number, isFollowing: boolean, followId?: number) => {
	// 不再自动刷新列表，只是记录状态变化
	// 按钮状态的改变由 FollowUserCard 组件内部处理
	// 列表数据只在下拉刷新时更新
	console.log(`用户 ${targetUserId} 关注状态变更为: ${isFollowing ? '已关注' : '已取消关注'}`)
}

// 返回上一页
const goBack = () => {
	uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.follow-fans-container {
	height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.custom-navbar {
	background: white;
	border-bottom: 1rpx solid #eee;
	z-index: 100;

	.navbar-content {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;

		.back-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.navbar-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
			flex: 1;
			text-align: center;
		}

		.placeholder {
			width: 60rpx;
		}
	}
}

.tab-container {
	position: relative;
	background: white;
	border-bottom: 1rpx solid #eee;

	.tab-list {
		display: flex;
		height: 88rpx;

		.tab-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 8rpx;
			transition: all 0.3s ease;
			cursor: pointer;

			.tab-text {
				font-size: 32rpx;
				color: #666;
				transition: color 0.3s ease;
			}

			.tab-count {
				font-size: 24rpx;
				color: #999;
			}

			&.active {
				.tab-text {
					color: #1890ff;
					font-weight: 600;
				}

				.tab-count {
					color: #1890ff;
				}
			}
		}
	}

	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 50%;
		height: 4rpx;
		background: #1890ff;
		transition: transform 0.3s ease;
		border-radius: 2rpx;
	}
}

.content-scroll {
	flex: 1;
	height: 0;
}

.content-container {
	padding: 24rpx;
}

.user-list {
	min-height: 400rpx;
}

.loading-container {
	display: flex;
	justify-content: center;
	padding: 60rpx 0;
}

.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 0;

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 32rpx;
		opacity: 0.6;
	}

	.empty-text {
		font-size: 32rpx;
		color: #666;
		margin-bottom: 16rpx;
	}

	.empty-tip {
		font-size: 28rpx;
		color: #999;
	}
}
</style>